import { Config } from '../utils/Config.js';

class Token{
  constructor() {
    this.tokenUrl= Config.restUrl+'token/user';
    this.verifyUrl= Config.restUrl + 'token/verify';
  }
  /**
   * 校验token
   */
  verify() {
    var token = wx.getStorageSync('token');
    if (!token) {
      //没有，去服务器请求token
      this.getTokenFromServer();
    }
    else {
      //有，去服务器校验token
      this._veirfyFromServer(token);
    }
  }
  /**
   * 去服务器校验token
   */
  _veirfyFromServer(token){
    var that = this;
    wx.request({
      url: that.verifyUrl,
      method: 'POST',
      data: {
        token: token
      },
      success: function (res) {
        var valid = res.data.valid;
        if (!valid){
          //校验失败，重新请求token
          that.getTokenFromServer();
        }
      }
    })
  }
  //去服务器请求token
  getTokenFromServer(callBack){
    var that = this;
    wx.login({
      success: function (res) {
        
        wx.request({
          url: that.tokenUrl,
          method: 'POST',
          data: {
            code: res.code
          },
          success: function (res) {
            wx.setStorageSync('token', res.data.data.token);
            callBack && callBack(res.data.data.token);
          }
        })
      }
    })
  }
}
export {Token};